new Vue(
				
    {
    el: '#app',

    data: {
        menuList: [{
            name: '主界面'
        }, {
            name: '异常检测'
        }, {
            name: '数据查询'
        }, {
            name: '系统设置'
        }],
        //初次实现对讲
        ws: null,
        mediaStack: null,
        audioCtx: null,
        scriptNode: null,
        source: null,
        play: true,
        //初次定义结束
        aurl:null,
        
        timeArry: "",
        mediaStream1:null,
        jsNode:null,
        leftDataList:[],
        rightDataList:[],
        wavBuffer:[],
        Larray:[],
        Rarray:[],
        allData:[],
        audioUrl:null,
        speed: 50, //速度
        status: 'success', //exception  低电量   获取电量后根据电量数值改变此值可区分高低电量
        indexOf: 0, //c菜单初始index
        value1: 10, //变焦初始
        value2: 0, //音量初始
        checked1: true, //报警开关
        checked2: true, //补光灯
        wavesurfer: null,
        percentage: 80, //电量
        warmingList: { //status默认为0为正常其他值均为报警 可随意更改
            vibe: [{
                name: '环境温度',
                status: <<my_dict.env_temper>>,
                msg: '<<my_dict.env_temper>>'+'°C',
                max:25
            }, {
                name: '环境湿度',
                status: <<my_dict.env_humidity>>,
                msg:'<<my_dict.env_humidity>>'+'%rh',
                max:1
            }, {
                name: '一氧化碳',
                status: <<my_dict.CO>>,
                msg:'<<my_dict.CO>>'+'mg/m3',
                max:1
            }, {
                name: '硫化氢',
                status: <<my_dict.HS>>,
                msg:'<<my_dict.HS>>'+'mg/m3',
                max:1
            }, {
                name: '氧气',
                status: <<my_dict.O2>>,
                msg:'<<my_dict.O2>>'+'mg/m3',
                max:1
            }, {
                name: '粉尘浓度',
                status: <<my_dict.dust>>,
                msg:'<<my_dict.dust>>'+'mg/m3',
                max:1
            }, {
                name: '可燃气体浓度',
                status: <<my_dict.gas>>,
                msg:'<<my_dict.gas>>'+'mg/m3',
                max:1
            }],
            robot: [{
                name: '温度',
                status: <<my_dict.rob_temper>>,
                msg:'<<my_dict.rob_temper>>'+'°C     ',
                max:25
            }, {
                name: '电量',
                status: -<<my_dict.power>>,
                msg:'<<my_dict.power>>'+'%    ',
                max:-10
            }, {
                name: '碰撞',
                status: <<my_dict.hit>>,
                max:0,
                msg:'<<my_dict.hit>>'+'处'
            }, {
                name: '通讯中断',
                status: <<my_dict.communication>>,
                msg:'<<my_dict.communication>>'+'处',
                max:0
            }, {
                name: '违规人员',
                status:<<my_dict.human>>,
                msg:'<<my_dict.human>>'+'人',
                max:0
            }, {
                name: '异常声音',
                status: <<my_dict.noise_alarm>>,
                msg:'<<my_dict.noise_alarm>>'+'处',
                max:0
            }, {
                name: '摄像头遮挡',
                status: <<my_dict.cam_alarm>>,
                msg:'<<my_dict.cam_alarm>>'+'处',
                max:0
            }, {
                name: '声光报警',
                status: <<my_dict.light_alarm>>,
                msg:'<<my_dict.light_alarm>>'+'处',
                max:0
            }]
        }
    },
    created: function() {
        this.timeArry = this.formatDate(new Date());
            this.timeStart()
    },
    mounted() {
        //音频波形初始化
        let that = this
        this.wavesurfer = WaveSurfer.create({
            container: '#waveform',
            waveColor: '#409EFF',
            cursorColor: '#ffad6e',
            progressColor: '#719dff',
        });
        this.wavesurfer.load('../static/img/1.mp3'); //音频地址
        this.wavesurfer.setVolume(this.value2)
        this.wavesurfer.on('ready', function() {
            that.wavesurfer.play();
        });
        this.startPlay();
    },
    methods: {
        //跳转页面实现
        checksql(){
            console.log("checksql")
            // $.ajax({
            // 	url:"/checksql",
            // 	data:{},
            // 	type:'GET',
            // 	success(res) {
            // 		console.log(res)
            // 	}
            // })
            window.location.href='http://localhost:5000/checksql'
            
              // this.$router.push({ path: "/checksql" });
            // console.log(this.$router.path)

             },

         //全新的对讲尝试
         initWs1() {
        // 连接 websocket,边端发送音频流
        const httpType = location.protocol === 'https:' ? 'wss://' : 'ws://'
        this.ws = new WebSocket(
            httpType + `localhost:8000/live/`
        )
        // this.ws = new WebSocket('ws://10.10.225.77:1041')
        this.ws.onopen = () => {
            console.log('socket 已连接')
        }
        this.ws.binaryType = 'arraybuffer'
        this.ws.onmessage = ({ data }) => {
            console.log(data)
            // 将接收的数据转换成与传输过来的数据相同的Float32Array
            const buffer = new Float32Array(data)
            // 创建一个空白的AudioBuffer对象，这里的4096跟发送方保持一致，48000是采样率
            const myArrayBuffer = this.audioCtx.createBuffer(1, 4096, 48000)
            // 也是由于只创建了一个音轨，可以直接取到0
            const nowBuffering = myArrayBuffer.getChannelData(0)
            // 通过循环，将接收过来的数据赋值给简单音频对象
            for (let i = 0; i < 4096; i++) {
            nowBuffering[i] = buffer[i]
            }
            // 使用AudioBufferSourceNode播放音频
            const source = this.audioCtx.createBufferSource()
            source.buffer = myArrayBuffer
            const gainNode = this.audioCtx.createGain()
            source.connect(gainNode)
            gainNode.connect(this.audioCtx.destination)
            var muteValue = 1
            if (!this.play) { // 是否静音
            muteValue = 0
            }
            gainNode.gain.setValueAtTime(muteValue, this.audioCtx.currentTime)
            source.start()
        }
        this.ws.onerror = (e) => {
            console.log('error', e)
        }
        this.ws.onclose = () => {
            console.log('socket closed')
        }
        },
        // 开始对讲
        startCall() {
        this.play = true
        this.audioCtx = new AudioContext()
        this.initWs1()
        // 该变量存储当前MediaStreamAudioSourceNode的引用
        // 可以通过它关闭麦克风停止音频传输

        // 创建一个ScriptProcessorNode 用于接收当前麦克风的音频
        this.scriptNode = this.audioCtx.createScriptProcessor(4096, 1, 1)
        navigator.mediaDevices
            .getUserMedia({ audio: true, video: false })
            .then((stream) => {
            this.mediaStack = stream
            this.source = this.audioCtx.createMediaStreamSource(stream)

            this.source.connect(this.scriptNode)
            this.scriptNode.connect(this.audioCtx.destination)
            })
            .catch(function (err) {
            /* 处理error */
            console.log('err', err)
            })
        // 当麦克风有声音输入时，会调用此事件
        // 实际上麦克风始终处于打开状态时，即使不说话，此事件也在一直调用
        this.scriptNode.onaudioprocess = (audioProcessingEvent) => {
            console.log('here', this.ws.readyState)
            const inputBuffer = audioProcessingEvent.inputBuffer
            // 由于只创建了一个音轨，这里只取第一个频道的数据
            const inputData = inputBuffer.getChannelData(0)
            // 通过socket传输数据，实际上传输的是Float32Array
            if (this.ws.readyState === 1) {

            this.ws.send(inputData)
            console.log('ready and data is',inputData)
            }
        }
        },
        // 关闭麦克风
        stopCall() {
        this.play = false
        this.mediaStack.getTracks()[0].stop()
        this.scriptNode.disconnect()
        console.log('关闭麦克风')
        },

        //全新对讲尝试结束
        //网络视频转码播放rmppg该段代码为后期提供另一种显示方法
        startPlay() {
            if (flvjs.isSupported()) {
                console.log('flvjs支持')
                const videoElement = document.getElementById("my_video");
                const videoElement2=document.getElementById("my_video2")
                const flvPlayer = flvjs.createPlayer(
                {
                    type: "flv",
                    isLive: true,
                    hasAudio: false,
                    //必须与node搭建的流媒体服务器中的http的端口和推流的参数吻合
                    url: "ws://localhost:8000/live/test.flv"
                },
                {
                    enableStashBuffer: true,
                    stashInitialSize: 128
                }
                );


                const flvPlayer2 = flvjs.createPlayer(
                {
                    type: "flv",
                    isLive: true,
                    hasAudio: false,
                    //必须与node搭建的流媒体服务器中的http的端口和推流的参数吻合
                    url: "ws://localhost:8000/live/test.flv"
                },
                {
                    enableStashBuffer: true,
                    stashInitialSize: 128
                }
                );

                flvPlayer.attachMediaElement(videoElement)
                flvPlayer2.attachMediaElement(videoElement2)
                flvPlayer.load()
                flvPlayer2.load()
                console.log(flvPlayer)
                flvPlayer.play()
                flvPlayer2.play()
            } else {
                console.log("flvjs不支持")
            }
            },
        

        getAjax(){
            $.ajax({
                url:"test.html",
                data:{},
                type:'GET',
                success(res) {
                    console.log(res)
                }
            })
        },

        //检测跨域问题函数
        ky(){
            console.log("KY url",this.audioUrl)
            document.querySelector('.audio1').src = this.audioUrl;

        },

        DXY() {
            console.log("print ",this.wavBuffer);
            // let data=new FormData();
            // data.append(this.wavBuffer)

            let data=this.wavBuffer
            axios.post('/api_message',data).then(res => {
                if(res.data.code == 200){
                    //做你后面的操作
                }else{
                    console.log('post fail')
                    //失败了可做弹框提示
                }})

            // $.ajax({
            // 	url:"/api_message",
            // 	data,
            // 	dataType:JSON,
            // 	type:'post',
            // 	success(res) {
            // 		console.log(res)
            // 	}
            // })
        },
        //改变音频音量
        changeVoice(e) {
            this.value2 = e
            this.wavesurfer.setVolume(this.value2)
        },
        //变焦
        changeZoom(e) {
            this.value1 = e
        },
        //摄像头上下左右移
        cameup(){
            console.log('摄像头上移')
            $.ajax({
                url:"/cameup",
                data:{},
                type:'GET',
                success(res) {
                    console.log(res)
                }
            })
        },
        camedown(){
            console.log('摄像头下移')
            $.ajax({
                url:"/camedown",
                data:{},
                type:'GET',
                success(res) {
                    console.log(res)
                }
            })

        },
        cameleft(){
            console.log('摄像头左移')
            $.ajax({
                url:"/cameleft",
                data:{},
                type:'GET',
                success(res) {
                    console.log(res)
                }
            })

        },
        cameright(){
            console.log('摄像头右移')
            $.ajax({
                url:"/cameright",
                data:{},
                type:'GET',
                success(res) {
                    console.log(res)
                }
            })

        },
        //变焦
        zoomup(){
            console.log('变焦增大')
            $.ajax({
                url:"/zoomup",
                data:{},
                type:'GET',
                success(res) {
                    console.log(res)
                }
            })

        },
        zoomdown(){
            console.log('变焦减小')
            $.ajax({
                url:"/zoomdown",
                data:{},
                type:'GET',
                success(res) {
                    console.log(res)
                }
            })

        },
        //下面是robot方向控制
        robotforward(){
            console.log('机器人前进')
            $.ajax({
                url:"/robotforward",
                data:{},
                type:'GET',
                success(res) {
                    console.log(res)
                }
            })

        },
        robotback(){
            console.log('机器人后退')
            $.ajax({
                url:"/robotback",
                data:{},
                type:'GET',
                success(res) {
                    console.log(res)
                }
            })

        },
        robotleft(){
            console.log('机器人向左')
            $.ajax({
                url:"/robotleft",
                data:{},
                type:'GET',
                success(res) {
                    console.log(res)
                }
            })

        },
        robotright(){
            console.log('机器人向右')
            $.ajax({
                url:"/robotright",
                data:{},
                type:'GET',
                success(res) {
                    console.log(res)
                }
            })

        },



        //拍照
        toPhotograph() {
            console.log('拍照执行')
            $.ajax({
                url:"/takephoto",
                data:{},
                type:'GET',
                success(res) {
                    console.log(res)
                }
            })
        },
        //录像
        toVideotape() {
            console.log('录像执行')
            $.ajax({
                url:"/videosave",
                data:{},
                type:'GET',
                success(res) {
                    console.log(res)
                }})

        },
        //静音
        toMute() {
            console.log('静音执行')
        },
        //对讲（废弃了）
        toIntercom() {
            window.navigator.mediaDevices.getSupportedConstraints({
                audio:true
            }).then(MediaStream=>{console.log(MediaStream);beginRecord(MediaStream);}).catch(err=>{console.log(err);})
            console.log('对讲执行')
        },
        //以下开始实现播放本地的音频
        playMusic (input) {
                console.log("执行本地播放")
                if (window.FileReader) {
                  var file = input.target.files[0];
                  var reader = new FileReader();
                console.log(file);
                // fileReader.onload = function () {
                // 		let arrayBuffer = this.result;
                // 		// 转成一个blob
                // 		let blob = new Blob([new Int8Array(this.result)]);
                // 		// 生成一个本地的blob url
                // 		let blobUrl = URL.createObjectURL(blob);
                // 		console.log(blobUrl);
                // 		// 给audio标签的src属性
                // 		document.querySelector('.audio-node').src = blobUrl;
                // 	};


                                                // if (!this.value) {
                // 	console.log(this.value)
                // 	return;
                // }
                // let fileReader = new FileReader();
                // let file = this.files[0];
                // fileReader.onload = function () {
                // 	let arrayBuffer = this.result;
                // 	console.log(arrayBuffer);
                // }
                // console.log(fileReader.readAsArrayBuffer(file));

                }
            },

        //本地音频播放结束

        //以下开始实现对讲录音功能。

        createWavFile (audioData) {
        console.log('打印audioData.length',audioData.length)
        const WAV_HEAD_SIZE = 44;
        let buffer = new ArrayBuffer(audioData.length * 2 + WAV_HEAD_SIZE),
            // 需要用一个view来操控buffer
            view = new DataView(buffer);
        // 写入wav头部信息
        // RIFF chunk descriptor/identifier
        this.writeUTFBytes(view, 0, 'RIFF');
        // RIFF chunk length
        view.setUint32(4, 44 + audioData.length * 2, true);
        // RIFF type
        this.writeUTFBytes(view, 8, 'WAVE');
        // format chunk identifier
        // FMT sub-chunk
        this.writeUTFBytes(view, 12, 'fmt ');
        // format chunk length
        view.setUint32(16, 16, true);
        // sample format (raw)
        view.setUint16(20, 1, true);
        // stereo (2 channels)
        view.setUint16(22, 2, true);
        // sample rate
        view.setUint32(24, 44100, true);
        // byte rate (sample rate * block align)
        view.setUint32(28, 44100 * 2, true);
        // block align (channel count * bytes per sample)
        view.setUint16(32, 2 * 2, true);
        // bits per sample
        view.setUint16(34, 16, true);
        // data sub-chunk
        // data chunk identifier
        this.writeUTFBytes(view, 36, 'data');
        // data chunk length
        view.setUint32(40, audioData.length * 2, true);
        let length = audioData.length;
        let index = 44;
        let volume = 1;
        for (let i = 0; i < length; i++) {
            view.setInt16(index, audioData[i] * (0x7FFF * volume), true);
            index += 2;
        }
        return buffer;
    },
    writeUTFBytes (view, offset, string) {
        var lng = string.length;
        for (var i = 0; i < lng; i++) { 
            view.setUint8(offset + i, string.charCodeAt(i));
        }
    },
    
        interleaveLeftAndRight (left, right) {//交叉合并左右声道
            let totalLength = left.length + right.length;
            let data = new Float32Array(totalLength);
            for (let i = 0; i < left.length; i++) {
                let k = i * 2;
                data[k] = left[i];
                data[k + 1] = right[i];
            }
            return data;
        },
        mergeArray (list) {//函数功能：将数据合并为一个数组
            let length = list.length * list[0].length;
            console.log(list.length)
            console.log(list[0].length)
            let data = new Float32Array(length),
                offset = 0;
            for (let i = 0; i < list.length; i++) {
                data.set(list[i], offset);
                offset += list[i].length;
            }
            //console.log('打印mergeArray中data的长度',data.length)
            return data;
        },
        
        onAudioProcess (event) {//函数功能：将缓冲数据压入列表
            
            // console.log(event.inputBuffer);
            let audioBuffer = event.inputBuffer;
            let leftChannelData = audioBuffer.getChannelData(0),
                rightChannelData = audioBuffer.getChannelData(1);
            this.leftDataList.push(leftChannelData.slice(0));
            this.rightDataList.push(rightChannelData.slice(0));
            //console.log(this.leftDataList, this.rightDataList);
            
        },
        playRecord1 (arrayBuffer) {
                let blob = new Blob([new Uint8Array(arrayBuffer)]);
                let blobUrl = URL.createObjectURL(blob);
                document.querySelector('.audio-node').src = blobUrl;
                console.log("打印arrBuffer");
                console.log(arrayBuffer);
                console.log("打印音频输出url");
                console.log(blobUrl);
                this.audioUrl=blobUrl;
                //释放内存
                //URL.revokeObjectURL(blobUrl);
            },
        stopRecord () {
            // 停止录音
            console.log('停止录音');
            this.mediaStream1.getAudioTracks()[0].stop();
            this.mediaNode.disconnect();
            
            this.jsNode.disconnect();
            //  console.log(this.leftDataList[0].length)
              this.Larray=this.mergeArray(this.leftDataList);
              this.Rarray=this.mergeArray(this.rightDataList);
            this.allData=this.interleaveLeftAndRight(this.Larray,this.Rarray);
            console.log("打印清空前this.allData",this.allData)
            
            this.wavBuffer = this.createWavFile(this.allData);
            // console.log(this.wavBuffer)
            this.playRecord1(this.wavBuffer)
            let data=this.wavBuffer
            axios.post('/saveaudio',data).then(res => {
                if(res.data.code == 200){
                    //做你后面的操作
                }else{
                    console.log('post fail')
                    //失败了可做弹框提示
                }})
            
            //console.log(this.Larray, this.Rarray);
            //清空数组
            // wavBuffer=[];
            // this.allData=[];
            // this.Larray=[];
            // this.Rarray=[];
            // this.jsNode=null;
            // this.mediaStream1=null;
            // this.mediaNode=null;
            this.leftDataList=[];
            this.rightDataList=[];
            console.log('打印清空后this.allData',this.allData)

        },


        beginRecord (mediaStream) {
            let audioContext = new (window.AudioContext || window.webkitAudioContext);
            this.mediaNode = audioContext.createMediaStreamSource(mediaStream);
            mediaNode1=audioContext.createMediaStreamSource(mediaStream)
                                    // 创建一个jsNode
            this.jsNode = this.createJSNode(audioContext);
            // 需要连到扬声器消费掉outputBuffer，process回调才能触发
            // 并且由于不给outputBuffer设置内容，所以扬声器不会播放出声音
            this.jsNode.connect(audioContext.destination);
            this.jsNode.onaudioprocess = this.onAudioProcess;
            // 把mediaNode连接到jsNode
            // this.jsNode.createObjectURL
            this.mediaNode.connect(this.jsNode);
            console.log("打印audioContext.destination",audioContext.destination)
            mediaNode1.connect(audioContext.destination);
            
        },
        record () {
            let that=this
            window.navigator.mediaDevices.getUserMedia({
                audio: {
                            sampleRate: 44100, // 采样率
                            channelCount: 2,   // 声道
                            //volume: 1.0        // 音量
                        }
                //audio: true
            }).then(mediaStream => {
                this.mediaStream1=mediaStream;
                console.log('开始录音');
                console.log(mediaStream);
                this.beginRecord(this.mediaStream1);
            }).catch(err => {
                // 如果用户电脑没有麦克风设备或者用户拒绝了，或者连接出问题了等
                // 这里都会抛异常，并且通过err.name可以知道是哪种类型的错误 
                console.error(err);
            })  ;
        },
        createJSNode (audioContext) {
            const BUFFER_SIZE = 4096;
            const INPUT_CHANNEL_COUNT = 2;
            const OUTPUT_CHANNEL_COUNT = 2;
            // createJavaScriptNode已被废弃
            let creator = audioContext.createScriptProcessor || audioContext.createJavaScriptNode;
            creator = creator.bind(audioContext);
            return creator(BUFFER_SIZE,
                            INPUT_CHANNEL_COUNT, OUTPUT_CHANNEL_COUNT);
        },	
        //录音功能执行完毕


        //手动
        toManual() {
            console.log('手动执行')
            $.ajax({
                url:"/toManual",
                data:{},
                type:'GET',
                success(res) {
                    console.log(res)
                }
            })

        },
        //巡航
        toCruise() {
            console.log('巡航执行')
            $.ajax({
                url:"/toCruise",
                data:{},
                type:'GET',
                success(res) {
                    console.log(res)
                }
            })
        },
        //回巢
        toHoming() {
            console.log('回巢执行')
            $.ajax({
                url:"/toHoming",
                data:{},
                type:'GET',
                success(res) {
                    console.log(res)
                }
            })
        },
        //充电
        toCharge() {
            console.log('充电执行')
            $.ajax({
                url:"/toCharge",
                data:{},
                type:'GET',
                success(res) {
                    console.log(res)
                }
            })
        },
        //时间
        formatDate(date) {
            // 格式化时间为 YYYY-MM-DD HH:MM:SS
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var day = date.getDate();
            var hours = date.getHours();
            var minutes = date.getMinutes();
            var seconds = date.getSeconds(); // 判断是不是小于10 返回01 02 03
            function check(num) {
                if (num < 10) {
                    // 如果数字小于10,前边拼接个0
                    return "0" + num;
                } else {
                    return num;
                }
            }
            let timeArry = {};
            let timeText =
                `${check(year)}年${check(month)}月${check(day)}日  ${check(hours)}: ${check(minutes)}: ${check(seconds)}`;
            let nowDay = date.getDay();
            let weeks = new Array(
                "星期日",
                "星期一",
                "星期二",
                "星期三",
                "星期四",
                "星期五",
                "星期六"
            );
            let week = weeks[
                nowDay
            ]; // let state = ``; // // 判断当前时间段 // if (hours >= 0 && hours <= 10) { //   state = `早上`; // } else if (hours > 10 && hours <= 14) { //   state = `中午`; // } else if (hours > 14 && hours <= 18) { //   state = `下午`; // } else if (hours > 18 && hours <= 24) { //   state = `晚上`; // }
            timeArry.timeText = timeText;
            timeArry.week = week; // timeArry.state = state;
            return timeArry; // 时间展示 // return ` //         ${check(year)}年 //         ${check(month)}月 //         ${check(day)}日 //         ${check(hours)} : //         ${check(minutes)} : //         ${check(seconds)}`;

        },
        timeStart() {
            this.timer = setInterval(() => {
                this.timeArry = this.formatDate(new Date());
            }, 1000);
        }
    }
})